package com.wongxd.webplayphone;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.wongxd.webplayphone.utilcode.util.NetworkUtils;

import java.util.List;

public class MainActivity extends AppCompatActivity {


    private boolean isStart = false;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        TextView tv = findViewById(R.id.tv_config);

        String ip = NetworkUtils.getIPAddress(true);

        tv.setText(getString(R.string.app_name) + "  用于在电脑上播放手机中的视频文件 \n\n" +
                "" +
                "请确保您要访问的电脑是与手机处在同一局域网中（由一个路由器代理）\n" +
                "\n" +
                "在电脑浏览器中输入: " +
                ip + ":51994\n" +
                "\n" +
                "然后点击对应的列表文件即可");

        final TextView tvState = findViewById(R.id.tv_state);
        final Button btn = findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this, BackService.class);
                if (isStart) {
                    stopService(i);
                    btn.setText("启动");
                    tvState.setText("关闭");
                } else {
                    startService(i);
                    btn.setText("关闭");
                    tvState.setText("启动");
                }
                isStart = !isStart;
            }
        });



        if (isServiceWork(this, "com.wongxd.playmp4onphone.BackService")) {
            btn.setText("关闭");
            tvState.setText("启动");
            isStart = true;
            Log.e("服务状态", " " + isStart);
        } else btn.performClick();

    }


    /**
     * 判断某个服务是否正在运行的方法
     *
     * @param mContext
     * @param serviceName 是包名+服务的类名（例如：net.loonggg.testbackstage.TestService）
     * @return true代表正在运行，false代表服务没有正在运行
     */
    public boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(100);
        if (myList.size() <= 0) {
            return false;
        }
        int size = myList.size();
        for (int i = 0; i < size; i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }

}
